package mvc.gui.impl.thumbnailspanel;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;

import mvc.core.IMachuPicchu;
import mvc.core.impl.MachuImage;

public class ThumbnailsPanelPresenter implements PropertyChangeListener,
		ActionListener {
	private ThumbnailsPanel panel;
	private IMachuPicchu machu;
	private List<ThumbnailButton> selectedList = new ArrayList();

	public ThumbnailsPanelPresenter(IMachuPicchu machuPicchu,
			ThumbnailsPanel thumbnail) {
		;
		this.machu = machuPicchu;
		machu.addPropertyChangeListener(this);
		this.panel = thumbnail;

	}

	/*
	 * listens to Model. Updates Thumbnails when changed has occured. Also sets
	 * an image as selected a default image based on which is first in
	 * imageList. (non-Javadoc)
	 * 
	 * @seejava.beans.PropertyChangeListener#propertyChange(java.beans.
	 * PropertyChangeEvent)
	 */
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("imageListChanged")) {
			panel.thumbnailsPanel.removeAll();
			if (machu.getImageList().size() > 0) {
				for (MachuImage i : machu.getImageList()) {
					Image img = i.getThumbnail();
					if (img == null) {

						try {
							img = machu.getImageProcessor().getFullSizeImage(i);
							if (img.getWidth(null) > img.getHeight(null)) {
								img = machu.getScaledImage(img, 150, -1);
							} else {
								img = machu.getScaledImage(img, -1, 150);
							}

							i.setThumbnail(img);
							System.out.println("Satt thumbnail till: "
									+ i.getFile());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					ThumbnailButton b = new ThumbnailButton(new ImageIcon(img),
							machu, i);

					b.addActionListener(this);

					panel.thumbnailsPanel.add(b);
				}
				panel.validate();
			}

		}

	}

	/*
	 * Listens on when a button is pressed to update wich thumbnail to be
	 * selected.
	 * 
	 * @see
	 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() instanceof ThumbnailButton) {
			ThumbnailButton button = ((ThumbnailButton) e.getSource());
			if (button.isSelected() == false) {
				button.setSelected();
				for (ThumbnailButton i : selectedList) {
					i.setUnselected();
				}
				selectedList = null;
				selectedList = new ArrayList<ThumbnailButton>();
				selectedList.add(button);
				List<MachuImage> list = new ArrayList<MachuImage>();
				list.add(button.getMachuImage());
				machu.setSelectedImages(list);
			} else {
				button.setUnselected();
				selectedList.remove(button);
			}
		}

	}

}
